import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: JSON.parse(localStorage.getItem('cartItems')) || [],
  }),

  getters: {
    // 购物车商品总数
    totalCount: (state) => {
      return state.items.reduce((total, item) => total + item.quantity, 0)
    },

    // 购物车总价
    totalPrice: (state) => {
      return state.items.reduce(
        (total, item) => total + item.price * item.quantity,
        0
      )
    },

    // 格式化总价
    formattedTotalPrice: (state) => {
      const total = state.items.reduce(
        (total, item) => total + item.price * item.quantity,
        0
      )
      return '¥' + (total / 100).toFixed(2)
    },
  },

  actions: {
    // 添加商品到购物车
    addToCart(product) {
      const existingItem = this.items.find((item) => item.id === product.id)

      if (existingItem) {
        existingItem.quantity += product.quantity || 1
      } else {
        this.items.push({
          ...product,
          quantity: product.quantity || 1,
        })
      }

      this.saveToLocalStorage()
    },

    // 更新商品数量
    updateQuantity(productId, quantity) {
      const item = this.items.find((item) => item.id === productId)
      if (item) {
        if (quantity <= 0) {
          this.removeFromCart(productId)
        } else {
          item.quantity = quantity
          this.saveToLocalStorage()
        }
      }
    },

    // 从购物车移除商品
    removeFromCart(productId) {
      const index = this.items.findIndex((item) => item.id === productId)
      if (index > -1) {
        this.items.splice(index, 1)
        this.saveToLocalStorage()
      }
    },

    // 清空购物车
    clearCart() {
      this.items = []
      this.saveToLocalStorage()
    },

    // 保存到本地存储
    saveToLocalStorage() {
      localStorage.setItem('cartItems', JSON.stringify(this.items))
    },
  },
})
